package com.example.springboot.config.event.transaction;

import com.example.springboot.dao.UserRepository;
import com.example.springboot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/9/26 16:24
 */
@Service
public class EventService {
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    @Autowired
    private UserRepository userRepository;

    @Transactional
    public void createUser() {
        // 创建用户
        User user = doCreateUser();
        // 创建用户成功，发送邮件，但是不要影响创建用户的回滚
        applicationEventPublisher.publishEvent(new UserCreateEvent(user));
    }

    private User doCreateUser() {

        User user = new User();
        user.setEmail("4545454");
        user.setLastName("czkkkk");
        userRepository.save(user);
        return user;
    }
}
